using System;
using System.Collections.Generic;
using System.Windows.Forms;
using DevExpress.XtraEditors.DXErrorProvider;

namespace Comteck.Winforms.Validations {
  /// <summary>
  /// 多个验证规则的匹配
  /// </summary>
  public class MultiValidationRule : ValidationRule {
    private readonly IEnumerable<MvcValidationRule> ruleList;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="ruleList"></param>
    public MultiValidationRule(IEnumerable<MvcValidationRule> ruleList) {
      // 规则
      this.ruleList = ruleList;
    }

    /// <summary>
    /// 验证结果
    /// </summary>
    /// <param name="control"></param>
    /// <param name="value"></param>
    /// <returns></returns>
    public override bool Validate(Control control, object value) {
      var errorMessageList = new List<string>();
      var flag = true;

      // 逐个验证
      foreach (var mvcRule in ruleList) {
        switch (mvcRule.ValidationType) {
          case MvcValidationType.RequiredAttribute:
            // 必须输入
            if (value.Is(EnumValidateType.NotNull) == false) {
              flag = false;
              errorMessageList.Add(mvcRule.ErrorMessage);
            }

            break;
          case MvcValidationType.MaxLengthAttribute:
            // 最大长度
            if (value != null && value.ToString().Length > mvcRule.MaxLength) {
              flag = false;
              errorMessageList.Add(mvcRule.ErrorMessage);
            }

            break;
          case MvcValidationType.MinLengthAttribute:
            // 最小长度
            if (value == null || value.ToString().Length < mvcRule.MinLength) {
              flag = false;
              errorMessageList.Add(mvcRule.ErrorMessage);
            }

            break;
          case MvcValidationType.MinValueAttribute: // 最小值
            if (value == null || value.To<double>() < mvcRule.MinValue) {
              flag = false;
              errorMessageList.Add(mvcRule.ErrorMessage);
            }

            break;
          case MvcValidationType.MaxValueAttribute: // 最大值
            if (value == null || value.To<double>() > mvcRule.MaxValue) {
              flag = false;
              errorMessageList.Add(mvcRule.ErrorMessage);
            }

            break;
          case MvcValidationType.CompareAttribute:
            break;
        }
      }

      this.ErrorText = string.Join(Environment.NewLine, errorMessageList);
      return flag;
    }
  }
}
